"""
实现了一个装饰器， login_required
如果需要调用被装饰的函数，你需要已经登录了
@login_required
def index():pass
1.全局变量：user = None => 未登录：请先登录再访问
                    not None => 已经登录: 调用index
2.将用户数据保存到文件，从文件中读取用户信息.
"""

import json


def Login_Required(func):
    def Inner(*args, **kwargs):
        if not user:
            print("未登录：请先登录再访问！")
        else:
            result = func(*args, **kwargs)
            return result

    return Inner


def Register():
    user_name = input("请输入想注册的用户名:")
    if user_name in user_dict:
        print("用户名已经注册！")
        return
    password = input("请输入用户的密码:")
    user_dict[user_name] = password


def Login():
    global user
    username = input("请输入用户名:")
    passwd = input("请输入密码:")
    if username in user_dict and passwd == user_dict[username]:
        print("登录成功!")
        user = username
    else:
        print("用户名或密码错误, 请重新输入。")


@Login_Required
def Show_All_User():
    print("已经注册的用户有:")
    for i in user_dict:
        print(i, end=" ")


@Login_Required
def Show_User():
    print(f"当前登录的用户:{user}")


@Login_Required
def Show_All_User():
    print("已经注册的用户有:")
    for i in user_dict:
        print(i, end=" ")


user = ""
with open("user.txt", "r", encoding="utf-8") as fp:
    user_file = fp.read()
    user_dict = json.loads(user_file)
print(user_dict)

while True:
    menu = """
    1.注册
    2.登录
    3.展示用户信息
    4.展示所有用户信息
    5.退出
    """
    print(menu)
    choice_menu = {'1': Register, "2": Login, "3": Show_User, "4": Show_All_User}
    choice = input("请做出你的选择:")
    if choice in choice_menu:
        choice_menu[choice]()
    elif choice == "5":
        break
    else:
        print("选择错误, 请选择1—4的选项!")

with open("user.txt", "w", encoding="utf-8") as f:
    user_menu = json.dumps(user_dict)
    f.write(user_menu)
